package com.autumn.platform.web.jsonbody;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.convert.TypeDescriptor;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.autumn.platform.web.resulthandler.wrapper.ResultWrapper;

@ControllerAdvice
public class JsonBodyControllerAdvice implements ResponseBodyAdvice<Object> {

    @Autowired(required = false)
    private ResultWrapper wrapper;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return AbstractJackson2HttpMessageConverter.class.isAssignableFrom(converterType)//
                || JsonBodyHttpMessageConverter.class.isAssignableFrom(converterType);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        TypeDescriptor type = new TypeDescriptor(returnType);
        if (JsonBodySupport.hasJsonBody()) {
            JsonBodySupport.setTypeDescriptor(type);
        }
        if (null != wrapper) {
            return wrapper.wrap(body, returnType);
        }
        return body;
    }

    public ResultWrapper getWrapper() {
        return wrapper;
    }

    public void setWrapper(ResultWrapper wrapper) {
        this.wrapper = wrapper;
    }
}
